package com.yx.fx.common.utils;

import cn.hutool.json.JSONObject;
import org.gavaghan.geodesy.Ellipsoid;
import org.gavaghan.geodesy.GeodeticCalculator;
import org.gavaghan.geodesy.GeodeticCurve;
import org.gavaghan.geodesy.GlobalCoordinates;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.URL;
import java.net.URLConnection;

public class GaoDeUtil {
    //1.根据两个地点得经纬度获取两个地点得直线距离,单位M（米）
    public static Double getDistance(Double aLongitude,Double aLatitude,Double bLongitude,Double bLatitude){
        GlobalCoordinates a = new GlobalCoordinates(aLongitude, aLatitude);
        GlobalCoordinates b = new GlobalCoordinates(bLongitude, bLatitude);
        //创建GeodeticCalculator，调用计算方法，传入坐标系、经纬度用于计算距离
        GeodeticCurve geoCurve = new GeodeticCalculator().calculateGeodeticCurve(Ellipsoid.Sphere,a,b);
        return geoCurve.getEllipsoidalDistance();
    }
    //2.根据地址获取高德经纬度
    public static String getLocation(String address) {
        StringBuffer json = new StringBuffer();
        try {
            URL u = new URL("https://restapi.amap.com/v3/geocode/geo?address=" + address + "&output=JSON&key=347c06c4f87aac426910309694600d93");
            URLConnection yc = u.openConnection();
            //读取返回的数据
            BufferedReader in = new BufferedReader(new InputStreamReader(yc.getInputStream(), "UTF-8"));
            String inputLine = null;
            while ((inputLine = in.readLine()) != null) {
                json.append(inputLine);
            }
            in.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
        String jsonStr = json.toString();
        JSONObject jsonObject = new JSONObject(jsonStr);
        if (jsonObject.getJSONArray("geocodes").size() > 0) {
            String location = jsonObject.getJSONArray("geocodes").getJSONObject(0).get("location").toString();
            return location;
        } else {
            return null;
        }
    }
}
